package com.silver.weibo.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;

@Component
public class UploadImage {

    //public static final String STATIC_PATH = ClassUtils.getDefaultClassLoader().getResource("static").getPath();
    //public static String uploadPath = STATIC_PATH + "/upload";
    private static final Logger logger = LoggerFactory.getLogger(UploadImage.class);


    @Value("${file.uploadurl}")
    private String uploadPath;

    public String upload(MultipartFile image) throws IOException {

        //如果文件夹不存在，创建
        File fileP = new File(uploadPath);

        if (!fileP.isDirectory()) {
            //递归生成文件夹
            boolean b = fileP.mkdirs();
            //生成文件失败，返回
            if (!b) return "";
        }

        //File upFile = new File(uploadPath);
        if (!image.isEmpty()) {
            // 获取文件名
            String fileName = "" + image.getOriginalFilename();
            if (fileName.length() > 50) {
                fileName = fileName.substring(0, 45) + fileName.substring(fileName.length() - 5);
            }
            // 限制文件上传类型
            String contentType = image.getContentType();
            if ("image/jpeg".equals(contentType) || "image/jpg".equals(contentType)) {
                File file = new File(uploadPath, fileName);
                if (file.isFile() && file.exists()) {
                    fileName = String.valueOf(new Date().getTime()).substring(6) + fileName.substring(6);
                    file = new File(uploadPath, fileName);
                }
                // 完成文件的上传
                image.transferTo(file);

                return fileName;
            } else {
                logger.error("文件上传失败");
            }
        }
        return "";
    }
}
